package com.huyi.web.controller;

import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crfchina.model.ResultCrmUser;
import com.huyi.common.group.GroupA;
import com.huyi.common.result.APIResponse;
import com.huyi.web.domain.SylarOrderDto;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by hsl on 2018/6/15.
 *
 * ***两种请求第三方接口方式
 */
@Slf4j
@RestController
@RequestMapping("/demo")
public class DemoController {

/*	@Autowired
	private CrmQuotaService crmQuotaService;
	
	@Autowired
	private ExecutorService executorService;*/
	
	@Autowired
	private CuratorFramework curator;

	/**
	 * post请求（参数json）
	 * 
	 * @param name
	 * @return
	 */
	@ApiOperation(value = "查询订单信息接口")
	@RequestMapping(value = "/rest/{indexId}", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject restIndex(@PathVariable("indexId") Integer indexId,
			@Validated(value = { GroupA.class }) @RequestBody SylarOrderDto dto, BindingResult bindingResult) throws Exception {
		// 打印日志
		log.info("接口调用start, index={}, crfUid={}", indexId, dto.getCrfUid());
		// 返回参数错误值
		if (bindingResult.hasErrors()) {
			FieldError fieldError = bindingResult.getFieldError();
			String validMsg = fieldError.getDefaultMessage();
			
			// 两种业务异常通用返回方式
			return APIResponse.returnError(validMsg);  		 // 一般用于controller层直接返回
			// throw new BizException(validMsg);				 // 一般用于service层抛出异常给controller返回
		}

		log.info("接口调用end...");
		return APIResponse.returnSuccess();
	}
	
	/**
	 * post请求（参数json）
	 * 
	 * @param name
	 * @return
	 */
	@ApiOperation(value = "查询客户额度信息接口")
	@RequestMapping(value = "/rest/dubbo", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject dubboIndex() throws Exception {
		// 打印日志
		log.info("调用dubbo接口start...");
		// CustomerQuota quota = customerQuotaService.getCustomerQuota("00106591d38a3553959ea5af4e55072d");
		// quota = dubboCrmQuotaService.getCustomerQuota("00106591d38a3553959ea5af4e55072d");
		ResultCrmUser user = null;
			// crmQuotaService.queryUser("34491acdee736d79ea0119870085373b", "hwj");
		log.info("接口调用end...");
		return APIResponse.returnSuccess(JSON.toJSONString(user));
	}

	/**
	 * post请求（参数json）
	 * 
	 * @param name
	 * @return
	 */
	@ApiOperation(value = "查询客户额度信息接口")
	@RequestMapping(value = "/rest/zookeeperLock", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject zookeeperLock() throws Exception {
		// 打印日志
		log.info("调用dubbo接口start...");
		InterProcessMutex mutex = null;
		SylarOrderDto dto = new SylarOrderDto();

		// 创建分布式锁, 锁空间的根节点路径为/curator/lock
		mutex = new InterProcessMutex(curator, "/curator/lock");
		
		// 无参数加锁
		// mutex.acquire();
		
		// 等待获取锁的超时时间、单位
		int time = 3000;
		boolean flag = mutex.acquire(time, TimeUnit.MILLISECONDS);
		if(flag) {
			try{
				log.info(curator + "已获取到锁...");
				Thread.sleep(100000);
				// 获得了锁, 进行业务流程
				dto.setCrfUid("111111111");
				dto.setProductType("2");
				dto.setOrderNo("2222222222");
				return APIResponse.returnSuccess(JSON.toJSONString(dto));
			} catch(Exception e) {
				log.error("加锁操作失败", e);
			} finally {
				// 完成业务流程, 释放锁
				if(mutex != null) {
					mutex.release();
				}
				log.info(curator + "锁释放");
			}
		} else{
			log.info(curator + "没有获取到锁");
			return APIResponse.returnError("没有获取到锁");
        }
		log.info("接口调用end...");
		return APIResponse.returnSuccess(JSON.toJSONString(dto));
		
	}
	
}
